﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using eShop.Business;
using eShop.Model;
using eShop.Utility;

public partial class admin_controls_category_form : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindFormDataToUI();
            BindModelToUI();
        }
    }

    protected void Save_Click(object sender, EventArgs e)
    {
        try
        {
            if (Page.IsValid)
            {
                SaveCategory();
                uccResponseMessage.SetSuccessMessage("Data saved successfully");
                uccResponseMessage.Visible = true;
            }
        }
        catch (Exception exception)
        {
            uccResponseMessage.SetFailMessage("Failed to save data." + "<br />" + exception.Message);
            uccResponseMessage.Visible = true;
        }
        finally
        {
            BindFormDataToUI();
            BindModelToUI();
        }
    }

    private void BindFormDataToUI()
    {
        List<KeyValuePair<int, string>> categories = new List<KeyValuePair<int, string>>();
        categories.Add(new KeyValuePair<int, string>(SiteUtility.SuperRootCategoryId, "None"));
        categories.AddRange(CategoryManager.GetAllFormatedActiveCategoriesWithSubCategory());
        ddlParent.DataSource = categories;
        ddlParent.DataBind();

        //cbxPartners.DataSource = ManufacturerManager.GetAllManufacturers();
        //cbxPartners.DataBind();
    }

    private void BindModelToUI()
    {
        if (Id > 0)
        {
            Category category = LoadCategory();
            BindCategoryToUI(category);
        }
        else
        {
            ClearUI();
        }
    }

    private void ClearUI()
    {
        tbxCategoryName.Text = string.Empty;
        ddlParent.SelectedIndex = 0;
        tbxDisplayOrder.Text = string.Empty;
        imgCategoryImage.ImageUrl = string.Empty;
        imgCategoryImage.Visible = false;
        imgCategoryBannerImage.ImageUrl = string.Empty;
        imgCategoryBannerImage.Visible = false;
        cbxIsActive.Checked = false;
        ddlParent.SelectedIndex = 0;
        //SetSelectedManufacturers(new List<int>());
    }

    private void BindCategoryToUI(Category category)
    {
        tbxCategoryName.Text = category.CategoryName;
        tbxDisplayOrder.Text = category.DisplayOrder.ToString();
        cbxIsActive.Checked = category.IsActive;
        ddlParent.SelectedValue = category.ParentCategoryId.ToString();
        if (!string.IsNullOrEmpty(category.CategoryImageUrl))
        {
            imgCategoryImage.ImageUrl = category.CategoryImageUrl;
            imgCategoryImage.Visible = true;
        }
        if (!string.IsNullOrEmpty(category.CategoryBannerImageUrl))
        {
            imgCategoryBannerImage.ImageUrl = category.CategoryBannerImageUrl;
            imgCategoryBannerImage.Visible = true;
        }
        List<Manufacturer> manufacturers = ManufacturerManager.GetByProductCategory(category.Id);
        List<int> manufacturerIds = new List<int>();
        foreach (Manufacturer manufacturer in manufacturers)
        {
            manufacturerIds.Add(manufacturer.ProductBrandId);
        }
        //SetSelectedManufacturers(manufacturerIds);
    }

    private Category LoadCategory()
    {
        if (Id > 0)
        {
            return CategoryManager.GetCategoryById(Id);
        }
        else
        {
            return new Category();
        }
    }

    private void SaveCategory()
    {
        Category category = LoadCategory();
        category.CategoryName = tbxCategoryName.Text.Trim();
        category.CategoryTitle = Server.HtmlEncode(tbxCategoryName.Text.Trim());
        category.ParentCategoryId = Convert.ToInt32(ddlParent.SelectedItem.Value);
        category.DisplayOrder = Convert.ToInt32(tbxDisplayOrder.Text.Trim());
        category.IsActive = cbxIsActive.Checked;
        if (fluCategoryLogo.HasFile)
        {
            category.CategoryImageUrl = WebPresentationUtility.UploadImageAndValidate(ApplicationSettings.TemporaryFolderPath, fluCategoryLogo.PostedFile);
        }
        if (fluCategoryBanner.HasFile)
        {
            category.CategoryBannerImageUrl = WebPresentationUtility.UploadImageAndValidate(ApplicationSettings.TemporaryFolderPath, fluCategoryBanner.PostedFile);
        }

        if (category.Id > 0)
        {
            CategoryManager.UpdateCategory(category);
        }
        else
        {
            CategoryManager.CreateCategory(category);
        }
    }

    //private List<int> GetSelectedManufacturers()
    //{
    //    List<int> manufacturerIds = new List<int>();
    //    foreach (ListItem li in cbxPartners.Items)
    //    {
    //        if (li.Selected == true)
    //        {
    //            manufacturerIds.Add(Convert.ToInt32(li.Value));
    //        }
    //    }
    //    return manufacturerIds;
    //}

    //private void SetSelectedManufacturers(List<int> manufacturerIds)
    //{
    //    foreach (ListItem listItem in cbxPartners.Items)
    //    {
    //        listItem.Selected = false;
    //    }
    //    foreach( int manufacturerId in manufacturerIds)
    //    {
    //        ListItem listItem = cbxPartners.Items.FindByValue(manufacturerId.ToString());
    //        if (listItem != null)
    //            listItem.Selected = true;
    //    }
    //}

    private Int32? _id;
    private Int32 Id
    {
        get
        {
            if (!_id.HasValue)
            {
                try
                {
                    if (HttpContext.Current.Request.QueryString != null 
                        && !String.IsNullOrEmpty(HttpContext.Current.Request.QueryString["cid"]))
                    {
                        _id = Convert.ToInt32(HttpContext.Current.Request.QueryString["cid"]);
                    }
                    else
                    {
                        _id = -1;
                    }
                }
                catch
                {
                    _id = -1;
                }
            }
            return _id.Value;
        }
    }
}